package com.aliang.shopping.util;

import com.aliang.shopping.contact.SqlColumnConstant;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 针对热门搜索的redis工具
 */
@Component
@AllArgsConstructor
public class SearchHostUtil {

    private RedisTemplate redisTemplate;



    /**
     * 获得key数组里面key2元素的索引
     *
     * @param keyWord 关键字
     * @return
     */
    public Long rank(Object keyWord) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rank(SqlColumnConstant.HOT_SEARCH, keyWord);
    }

    /**
     * 有序集合添加
     *
     * @param value
     * @param scoure
     */
    public void add(Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(SqlColumnConstant.HOT_SEARCH, value, scoure);
    }

    /**
     * 获得key数组里面key2元素的排序值
     *
     * @param keyWord
     * @return
     */
    public double score(Object keyWord) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.score(SqlColumnConstant.HOT_SEARCH, keyWord);
    }

    /**
     * 从高到低的排序集中获取从头(start)到尾(end)内的元素。
     *
     * @param start
     * @param end
     * @return
     */
    public Set<Object> reverseRange(long start, long end) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.reverseRange(SqlColumnConstant.HOT_SEARCH, start, end);
    }

    /**
     * 根据分数保留指定个数，其余的元素删除
     *
     * @param number
     * @return
     */
    public Boolean remove(Integer number) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        Long size = zset.size(SqlColumnConstant.HOT_SEARCH);
        if (size > number) {
            //获取变量指定区间的元素
            Set<ZSetOperations.TypedTuple<Object>> typedTuples = zset.rangeWithScores(SqlColumnConstant.HOT_SEARCH, 0, (size - 1) - number);
            Set set = new HashSet();
            for (ZSetOperations.TypedTuple<Object> o : typedTuples) {
                set.add(o.getValue());
            }
            for (Object o : set) {
                Long aLong = zset.remove(SqlColumnConstant.HOT_SEARCH, o);
                if (aLong == null) {
                    return false;
                }
            }
            return true;
        } else {
            return true;
        }
    }
}
